<template>
    <div class="app-container">
        <span style="font-size: 26px;margin-right: 100px; margin-left: -60px; color: black;">购置农业机械补贴核实登记信息表</span>
        <el-button v-show="!readonly" :loading="buttonLoading" type="primary" @click="submitForm" style="padding: 10px 40px;">保存</el-button>
        <el-button :loading="buttonLoading" type="success" plain @click="exportPDF" :disabled="!isFormValid" style="margin-left: 20px; padding: 10px 40px; float: right;">导出PDF</el-button>
        <!-- <el-button @click="exportInfo" type="danger" plain size="medium" style="margin-left: 20px; padding: 10px 40px;">驳回</el-button> -->
        <!-- <el-button :loading="buttonLoading" plain @click="submitForm" style="margin-left: 20px; padding: 10px 40px; float: right; border: 1px solid black; color: black;">返回</el-button> -->
        <el-row :gutter="24">
            <el-form ref="elForm" :model="form" :disabled="readonly" :rules="rules" size="medium" label-width="120px" label-position="left">
                <div class="card-container">
                    <el-card class="infoDiv">
                        <span class="corner-label">农业所有人</span>
                        <el-row :gutter="15" style="margin-top: 40px;">
                            <el-col :span="10" :offset="1">
                                <el-form-item label="身份证号" prop="idCard">
                                    <el-input v-model="form.idCard" placeholder="请输入18位身份证号码" clearable></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="10" :offset="2">
                                <el-form-item label="姓名" prop="appyBy">
                                    <el-input v-model="form.appyBy" placeholder="请输入姓名" clearable></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="15" style="margin-top: 10px;">
                            <el-col :span="10" :offset="1">
                                <el-form-item label="银行账号" prop="bankCard">
                                    <el-input v-model="form.bankCard" placeholder="请输入银行账号" clearable></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="10" :offset="2">
                                <el-form-item label="联系电话" prop="phone">
                                    <el-input v-model="form.phone" placeholder="请输入联系电话" clearable></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-card>
                </div>
                <div class="card-container">
                    <el-card class="infoDiv">
                        <span class="corner-label">农业机械信息</span>
                        <el-row :gutter="15" style="margin-top: 40px; margin-bottom: 10px;">
                            <el-col :span="10" :offset="1">
                                <el-form-item label="登记编号" prop="regiNum">
                                    <el-input v-model="form.regiNum" placeholder="请输入登记编号" clearable></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="10" :offset="2">
                                <el-form-item label="机具大类" prop="machineType">
                                    <!-- <el-select v-model="form.machineType"
                                        :loading="loading" filterable remote reserve-keyword placeholder="请选择机具大类"
                                        :style="{ width: '100%' }" clearable>
                                        <el-option v-for="item in machineTypeList" :key="item.value" :label="item.label"
                                            :value="item.label" />
                                    </el-select> -->
                                    <el-input v-model="form.machineType" placeholder="请输入机具大类" clearable></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="15" style="margin-bottom: 10px; margin-top: 10px;">
                            <el-col :span="10" :offset="1">
                                <el-form-item label="品牌型号" prop="speModel">
                                    <el-input v-model="form.speModel" placeholder="请输入品牌型号" clearable></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="10" :offset="2">
                                <el-form-item label="功率（Kw）" prop="power">
                                    <el-input v-model="form.power" placeholder="请输入功率" clearable></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="15" style="margin-bottom: 10px; margin-top: 10px;">
                            <el-col :span="10" :offset="1">
                                <el-form-item label="发动机号" prop="machineEngine">
                                    <el-input v-model="form.machineEngine" placeholder="请输入发动机号" clearable></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="10" :offset="2">
                                <el-form-item label="出厂编号" prop="machineNum">
                                    <el-input v-model="form.machineNum" placeholder="请输入出厂编号" clearable></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="15" style="margin-bottom: 10px; margin-top: 10px;">
                            <el-col :span="10" :offset="1">
                                <el-form-item label="价格（元）" prop="price">
                                    <el-input v-model="form.price" placeholder="请输入价格" clearable></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="10" :offset="2">
                                <el-form-item label="补贴金额（元）" prop="moneySub">
                                    <el-input v-model="form.moneySub" placeholder="请输入补贴金额" clearable></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-card>
                </div>
                <div class="card-container">
                    <el-card class="infoDiv">
                        <span class="corner-label">生产销售信息</span>
                        <el-row :gutter="15" style="margin-top: 40px; margin-bottom: 10px;">
                            <el-col :span="10" :offset="1">
                                <el-form-item label="生产企业名称" prop="productCompany">
                                    <el-input v-model="form.productCompany" placeholder="请输入生产企业名称" clearable></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="10" :offset="2">
                                <el-form-item label="生产日期" prop="productDate">
                                    <el-input v-model="form.productDate" placeholder="请输入生产日期" clearable></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="15" style="margin-bottom: 10px; margin-top: 10px;">
                            <el-col :span="10" :offset="1">
                                <el-form-item label="销售企业名称" prop="saleCompany">
                                    <el-input v-model="form.saleCompany" placeholder="请输入销售企业名称" clearable></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="10" :offset="2">
                                <el-form-item label="销售日期" prop="saleDate">
                                    <el-input v-model="form.saleDate" placeholder="请输入销售日期" clearable></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="15" style="margin-bottom: 10px; margin-top: 10px;">
                            <el-col :span="10" :offset="1">
                                <el-form-item label="发票编号" prop="invoice">
                                    <el-input v-model="form.invoice" placeholder="请输入发票编号" clearable></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="15" style="margin-bottom: 10px; margin-top: 10px;">
                            <el-col :span="10" :offset="1">
                                <el-form-item label="人机合照" prop="renjiurl">
                                    <el-row>
                                        <el-col :span="18">
                                            <el-upload class="upload-demo" action="http://111.40.188.220:9060/subsidy/file/upload"
                                                :on-preview="handlePreview" :on-remove="(file) => handleRemove(file, 'renjiurl')"
                                                :on-success="(response, file) => handleSuccess(response, file, 'renjiurl')" :limit="1"
                                                :on-exceed="handleExceed" :file-list="uploadedImage" list-type="picture">
                                                <el-button icon="el-icon-upload" plain type="primary">上传图片</el-button>
                                            </el-upload>
                                            <div style="margin-top: 10px; color: #C1C1C1;">上传图片649 x 991px</div>
                                        </el-col>
                                        <!-- <el-col :span="4">
                                            图片
                                        </el-col> -->
                                    </el-row>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-card>
                </div>
                <div class="card-container">
                    <el-card class="infoDiv">
                        <span class="corner-label">申请资料</span>
                        <el-row :gutter="15" style="margin-top: 20px;">
                            <el-col :span="24" :offset="1" style="margin-bottom: 20px;">
                                <el-button  :type="selectMaterials ? '':'primary'"  style="padding: 10px 40px;" :disabled="!addState && !(form.appType == '农用机车')">农用机车</el-button>
                                <el-button  :type="!selectMaterials ? '':'primary'"  :disabled="!addState && !(form.appType == '农用配套机具')">农用配套机具</el-button>
                            </el-col>
                            <el-col :span="16" :offset="1">
                                <el-table :data="tableData[selectMaterials]" border  style="width: 100%">
                                    <el-table-column prop="name" label="申请资料名称" width="220" align="left">
                                        <template #default="scope">
                                            <span v-if="scope.row.required" style="color: red">*</span>
                                            <span v-else style="padding-left: 10px;">&nbsp;</span>
                                            {{ scope.row.name }}
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="address" label="申请资料附件" align="center">
                                        <!-- <template #default="scope">
                                            <el-upload class="upload-demo" action="http://111.40.188.220:9060/subsidy/file/upload"
                                                :on-preview="handlePreview" :on-remove="(file) => handleRemove(file, 'appyExcel')"
                                                :on-success="(response, file) => handleSuccess(response, file, 'appyExcel')" :limit="1"
                                                :on-exceed="handleExceed" :file-list="uploadedAppyExcel">
                                                <el-button icon="el-icon-upload" plain type="primary">点击上传</el-button>
                                            </el-upload>
                                        </template> -->
                                          <template #default="scope">
                                                <div v-if="!scope.row.file">
                                                    <el-upload
                                                        class="upload-demo"
                                                        action="http://111.40.188.220:9060/subsidy/file/upload"
                                                        :on-preview="handlePreview"
                                                        :on-success="(response, file) => handleSuccess(response, file, scope.row)"
                                                        :on-remove="(file) => handleRemove(file, scope.row)"
                                                        :on-exceed="handleExceed"
                                                        :limit="1"
                                                        :file-list="scope.row.fileList || []"
                                                    >
                                                        <el-button icon="el-icon-upload" plain type="primary">点击上传</el-button>
                                                    </el-upload>
                                                </div>
                                                <div v-else>
                                                    <el-button type="success" :disabled="false" @click="handlePreview(scope.row)">查看</el-button>
                                                    <el-button type="danger" :disabled="true" @click="() => handleRemove(scope.row.file, scope.row)">撤销</el-button>
                                                </div>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </el-col>
                        </el-row>
                    </el-card>
                </div>
                <div class="card-container">
                    <el-card class="infoDiv">
                        <span class="corner-label">附件信息</span>
                        <el-row :gutter="15" style="margin-top: 40px; margin-bottom: 10px;">
                            <el-col :span="24" :offset="1">
                                <el-form-item label-width="220px"  label="乡级补贴申请表" prop="areaAmount" >
                                    <el-col :span="6">
                                        <el-upload class="upload-demo" action="http://111.40.188.220:9060/subsidy/file/upload"
                                                :on-preview="handlePreview" :on-remove="(file) => handleRemove(file, 'townapplyurl')"
                                                :on-success="(response, file) => handleSuccess(response, file, 'townapplyurl')" :limit="1"
                                                :on-exceed="handleExceed" :file-list="uploadedApplication">
                                                <el-button icon="el-icon-upload" plain type="primary">上传附件</el-button>
                                            </el-upload>
                                    </el-col>        
                                    <span style="margin-left: 30px; color: #C1C1C1;">支持 .PDF 等格式，单个附件不得超过512M</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="15" style="margin-top: 40px; margin-bottom: 10px;">
                            <el-col :span="24" :offset="1">
                                <el-form-item label-width="220px"  label="区级核实登记信息表" prop="areaAmount">
                                    <el-col :span="6">
                                        <el-upload class="upload-demo" action="http://111.40.188.220:9060/subsidy/file/upload"
                                            :on-preview="handlePreview" :on-remove="(file) => handleRemove(file, 'disappurl')"
                                            :on-success="(response, file) => handleSuccess(response, file, 'disappurl')" :limit="1"
                                            :on-exceed="handleExceed" :file-list="uploadedSales">
                                            <el-button icon="el-icon-upload" plain type="primary">上传附件</el-button>
                                        </el-upload>
                                    </el-col>
                                    <span style="margin-left: 30px; color: #C1C1C1;">支持 .PDF 等格式，单个附件不得超过512M</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-card>
                </div>
            </el-form>
        </el-row>
    </div>
</template>
<script>
import { listSubsidyApplication, getMachineryDetail, delSubsidyApplication, addSubsidyApplication, updateSubsidyApplication, rejectSubsidyApplication, approveSubsidyApplication } from "@/api/machinery/compliehandle";
import { checkRole, checkPermi } from '@/utils/permission'
import {listMachingByName} from "@/api/machinery/compliehandle"
import { saveAs } from 'file-saver';
import PizZip from 'pizzip';
import ImageModule from 'docxtemplater-image-module-free';
import docxtemplater from 'docxtemplater';
import { parseTime, resetForm, addDateRange, selectDictLabel, selectDictLabels, handleTree } from "@/utils/ruoyi";
import { delFile } from '@/api/agriculture/file'

export default {
    computed: {
        isFormValid() {
            // 检查所有rules中required为true的字段是否有值
            const requiredFields = Object.keys(this.rules).filter(key => {
                const arr = this.rules[key];
                return arr && arr.some(rule => rule.required);
            });
            return requiredFields.every(field => {
                const val = this.form[field];
                return val !== undefined && val !== null && val !== '';
            });
        }
    },
    data() {
        return {
            // 按钮loading
            buttonLoading: false,
            borrow: {},
            readonly: false,
            uploadedImage: [], //上传图片url存储
            uploadedApplication: [], //上传图片url存储
            uploadedSales: [], //上传图片url存储
            exportPDFStatus: false, //导出PDF状态
            selectMaterials: 0,
            addState: true,
            form: {
                idCard: undefined,
                appyBy: undefined,
                sex: undefined,
                phone: undefined,
                fuzeren:undefined,
                bankCard: undefined,
                areaAmount: undefined,
                appType: undefined,
                remark: undefined,
                submitDate: undefined,
                //租借他人
                borrowName: undefined, 
                borrowArea: undefined,
                borrowPhone: undefined,
                // 机具信息
                machineName: undefined,
                productName: undefined,
                speModel: undefined,
                moneySub: undefined,
                licenseNum: undefined,

                straName: undefined,
                townName: undefined,
                villageName: undefined,
                submitBy: undefined,
                status: undefined,
                // appBigType: undefined,
                renjiurl: undefined,
                townapplyurl: undefined,
                disappurl: undefined,
            },
            rules: {
                idCard: [{
                    required: true,
                    message: '请输入身份证号码',
                    trigger: 'blur'
                }, 
                // {
                //     pattern: /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
                //     message: '请输入正确的身份证号',
                //     trigger: 'blur'
                // }
                ],
                appyBy: [{
                    required: true,
                    message: '请输入申请人',
                    trigger: 'blur'
                }],
                bankCard: [{
                    required: true,
                    message: '请输入一卡通账号',
                    trigger: 'blur'
                }],
                phone: [{
                    required: true,
                    message: '请输入联系方式',
                    trigger: 'blur'
                }, {
                    pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
                    message: '请输入正确的手机号',
                    trigger: 'blur'
                }],
                regiNum: [{
                    required: true,
                    message: '请输入登记编号',
                    trigger: 'blur'
                }],
                machineType: [{
                    required: true,
                    message: '请选择机具大类',
                    trigger: 'blur'
                }],
                speModel: [{
                    required: true,
                    message: '请输入品牌型号',
                    trigger: 'blur'
                }],
                power: [{
                    required: true,
                    message: '请输入功率',
                    trigger: 'blur'
                }],
                machineEngine: [{
                    required: true,
                    message: '请输入发动机号',
                    trigger: 'blur'
                }],
                machineNum: [{
                    required: true,
                    message: '请输入出产编号',
                    trigger: 'blur'
                }],
                price: [{
                    required: true,
                    message: '请输入价格',
                    trigger: 'blur'
                }],
                moneySub: [{
                    required: true,
                    message: '请输入补贴金额',
                    trigger: 'blur'
                }],
                productCompany: [{
                    required: true,
                    message: '请输入生产企业名称',
                    trigger: 'blur'
                }],
                productDate: [{
                    required: true,
                    message: '请输入生产日期',
                    trigger: 'blur'
                }],
                saleCompany: [{
                    required: true,
                    message: '请输入销售企业名称',
                    trigger: 'blur'
                }],
                saleDate: [{
                    required: true,
                    message: '请输入销售日期',
                    trigger: 'blur'
                }],
                invoice: [{
                    required: true,
                    message: '请输入发票编号',
                    trigger: 'blur'
                }],
                // sex: [{
                //     required: true,
                //     message: '请选择性别',
                //     trigger: 'change'
                // }],
                
                // idcardAddr: [{
                //     required: true,
                //     message: '请输入身份证地址',
                //     trigger: 'blur'
                // }],
                // oftenAddr: [{
                //     required: true,
                //     message: '请输入现住地址',
                //     trigger: 'blur'
                // }],
                
                // fuzeren:[{
                //     required: true,
                //     message: '请输入责任人',
                //     trigger: 'blur'
                // }],
                
                // appType: [{
                //     required: true,
                //     message: '请选择补贴类型',
                //     trigger: 'change'
                // }],
                remark: [],
            },
            sexOptions: [{
                "label": "男",
                "value": "男"
            }, {
                "label": "女",
                "value": "女"
            }],
            machineTypeList:[],
            tableData: [[
                {
                    key: "introductionUrl",
                    name: '1.村介绍信',
                    required: true,
                    file: null, 
                    fileList: []
                },
                {
                    key:"idCardFrontUrl",
                    name: '2.身份证（正面）',
                    required: true,
                    file: null, 
                    fileList: []
                },
                {
                    key:"idCardBackUrl",
                    name: '3.身份证（国徽面）',
                    required: true,
                    file: null, 
                    fileList: []
                },
                {
                    key: "hukouIndexUrl",
                    name: '4.户口首页',
                    required: true,
                    file: null, 
                    fileList: []
                },
                {
                    key: "hukouOwnerUrl",
                    name: '5.户口本人页',
                    required: true,
                    file: null, 
                    fileList: []
                },
                {
                    key: "machinecertFrontUrl",
                    name: '6.机器合格证（正面）',
                    required: false,
                    file: null, 
                    fileList: []
                },
                {
                    key: "machinecertBackUrl",
                    name: '7.机器合格证（反面）',
                    required: false,
                    file: null, 
                    fileList: []
                },
                {
                    key: "engineCertUrl",
                    name: '8.发动机合格证',
                    required: false,
                    file: null, 
                    fileList: []
                },
                {
                    key: "tractorCertUrl",
                    name: '9.拖拉机（收获机）行驶证',
                    required: true,
                    file: null, 
                    fileList: []
                },
                {
                    key: "driverCertUrl",
                    name: '10.拖拉机（收获机）驾驶证',
                    required: false,
                    file: null, 
                    fileList: []
                },
                {
                    key: "machineNameUrl",
                    name: '11.机车铭牌',
                    required: true,
                    file: null, 
                    fileList: []
                },
                {
                    key: "engineNameUrl",
                    name: '12.发动机铭牌',
                    required: true,
                    file: null, 
                    fileList: []
                },
                {
                    key: "manufacturingNameUrl",
                    name: '13.机器出厂编号（钢号）',
                    required: true,
                    file: null, 
                    fileList: []
                },
                {
                    key: "vinRubbingUrl",
                    name: '14.发动机编号（钢号）',
                    required: true,
                    file: null, 
                    fileList: []
                },
                {
                    key: "bankCardUrl",
                    name: '15.本人一卡通卡',
                    required: true,
                    file: null, 
                    fileList: []
                },
                {
                    key: "peopleMachineUrl",
                    name: '16.人机合影三寸',
                    required: true,
                    file: null, 
                    fileList: []
                },
                {
                    key: "invoiceUrl",
                    name: '17.发票复印件',
                    required: true,
                    file: null, 
                    fileList: []
                },
                {
                    key: "registrationUrl",
                    name: '18.落牌照发的登记证书',
                    required: true,
                    file: null, 
                    fileList: []
                },
                {
                    key: "paymentProofUrl",
                    name: '19.现金收据或者微信截图',
                    required: false,
                    file: null, 
                    fileList: []
                },
            ], 
            [
                {
                    key: "introductionUrl",
                    name: '1.村介绍信',
                    required: true,
                    file: null, 
                    fileList: []
                },
                {
                    key: "idCardFrontUrl",
                    name: '2.身份证（正面）',
                    required: true,
                    file: null, 
                    fileList: []
                },
                {
                    key: "idCardBackUrl",
                    name: '3.身份证（国徽面）',
                    required: true,
                    file: null, 
                    fileList: []
                },
                {
                    key: "hukouIndexUrl",
                    name: '4.户口首页',
                    required: true,
                    file: null, 
                    fileList: []
                },
                {
                    key: "hukouOwnerUrl",
                    name: '5.户口本人页',
                    required: true,
                    file: null, 
                    fileList: []
                },
                {
                    key: "machinecertFrontUrl",
                    name: '6.机器合格证',
                    required: true,
                    file: null, 
                    fileList: []
                },
                {
                    key: "machineNameUrl",
                    name: '7.机器铭牌',
                    required: true,
                    file: null, 
                    fileList: []
                },
                {
                    key: "manufacturingNameUrl",
                    name: '8.机器出厂编号',
                    required: false,
                    file: null, 
                    fileList: []
                },
                {
                    key: "bankCardUrl",
                    name: '9.本人一卡通卡',
                    required: true,
                    file: null, 
                    fileList: []
                },
                {
                    key: "peopleMachineUrl",
                    name: '10.人机合影三寸',
                    required: true,
                    file: null, 
                    fileList: []
                },
                {
                    key: "invoiceUrl",
                    name: '11.发票',
                    required: true,
                    file: null, 
                    fileList: []
                },
                {
                    key: "paymentProofUrl",
                    name: '12.现金收据或者微信截图',
                    required: false,
                    file: null, 
                    fileList: []
                },
            ]
            ],
        }
    },
    created() {
        const id = this.$route.query.id || this.$route.params.id;
        this.node = this.$route.query.node || this.$route.params.node;
        this.readonly = this.$route.query.readonly || this.$route.params.readonly;
        if (id) {
            this.loading = true
            this.fetchDetail(id);

        }
    },
    methods: {
        async getMachineTypeList(){
            try {
                const response = await listMachingByName({ machineName: this.form.machineName, 
                    productName: this.form.productName, speModel: this.form.speModel});
                if (response && response.length>0) {
                    // 转为 el-option 所需格式：{ value, label }
                    // this.machineTypeList = response.map((item,index) => ({
                    //     value: index,
                    //     label: item.bigType
                    // }));
                    this.form.machineType = response[0].bigType;
                    
                } else {
                    this.machineTypeList = [];
                }
            } catch (error) {
                this.$message.error('获取信息失败');
            }
        },
        async fetchDetail(id) {
            try {
                const res = await getMachineryDetail(id);
                if (res.code === 200 && res.data) {
                    console.log("res.data", res.data)
                    this.form = res.data;
                    console.log("获得值的表格",this.form)
                    // this.form.speModel = ''
                    this.getMachineTypeList()
                    this.peopleMachineUrlHandle()
                    this.attachmentHandel()
                    this.loading = false
                    // Object.keys(this.form).forEach(key => {
                    // if (res.data[key] !== undefined) {
                    //     this.form[key] = res.data[key];
                    // }
                    // });
                    this.addState = false;
                    if (this.form.appType == "农用机车") {
                        this.selectMaterials = 0
                    } else {
                        this.selectMaterials = 1
                    }
                    this.tableData[this.selectMaterials] = this.fillTableData(this.tableData[this.selectMaterials], this.form.attachments);
                }
            } catch (error) {
                this.$message.error('获取详情失败');
            }
        },
        fillTableData(tableData, attachmentsStr) {
            if (!attachmentsStr) return tableData
            let attachments = {}
            try {
                attachments = JSON.parse(attachmentsStr)
            } catch (e) {
                console.error("attachments JSON 解析失败", e)
                return tableData
            }

            // 遍历每一组 tableData
            return tableData.map(item => {
                const url = attachments[item.key] || ""
                return {
                    ...item,
                    file: url ? url : null,
                    fileList: url
                    ? [{ name: item.name, url }]
                    : []
                }
                }
            )
        },
        peopleMachineUrlHandle() {
            if (this.form.attachments) {
                let attachObj = {};
                try {
                    attachObj = JSON.parse(this.form.attachments);
                } catch (e) {
                    this.$message.error('附件信息解析失败');
                    return;
                }
                // 提取 peopleMachineUrl 字段
                const url = attachObj.peopleMachineUrl;
                if (url) {
                    this.form.renjiurl = url;
                    this.uploadedImage = [
                        {
                            name: '人机合照',
                            url: url.replace('172.24.254.135','111.40.188.220')
                        }
                    ];
                } else if (this.form.renjiurl) {
                    this.uploadedImage = [
                        {
                            name: '人机合照',
                            url: this.form.renjiurl.replace('172.24.254.135','111.40.188.220')
                        }
                    ];
                    
                }
            } else {
                this.uploadedImage = [];
                this.$message.error('未获取到人机合照');
            }
        },
        attachmentHandel() {
            if (!this.form.disappurl || !this.form.townapplyurl) {
                this.$message.error('未获取到附件信息');
            } else {
                this.uploadedApplication = [
                    {
                        name: '乡级补贴申请表',
                        url: this.form.townapplyurl.replace('172.24.254.135','111.40.188.220')
                    }
                ]
                this.uploadedSales = [
                    {
                        name: '区级核实登记信息表',
                        url: this.form.disappurl.replace('172.24.254.135','111.40.188.220')
                    }
                ]
            }
        },
        getFormattedDateTime() {
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需+1
            const day = String(now.getDate()).padStart(2, '0');
            const hours = String(now.getHours()).padStart(2, '0');
            const minutes = String(now.getMinutes()).padStart(2, '0');
            const seconds = String(now.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        submitForm: function () {
            
            this.form.submitDate = this.getFormattedDateTime();
            console.log("提交时间", this.form.submitDate)
            // this.form.status = '已完成'
            this.$refs['elForm'].validate(valid => {
                if (!this.form.townapplyurl || !this.form.disappurl) {
                    this.$modal.msgError("请上传附件再保存");
                    return;
                }
                if (!this.exportPDFStatus) {
                    this.$modal.msgError("保存前，请先导出");
                    return
                }
                if (valid) {
                    this.buttonLoading = true;
                        updateSubsidyApplication(this.form).then(response => {
                            // 保存成功后调用审核接口
                            if (response.code === 200) {
                                approveSubsidyApplication({ appNum: this.form.appNum }).then(auditRes => {
                                    if (auditRes.code === 200) {
                                        this.$modal.msgSuccess("保存并审核成功");
                                    } else {
                                        this.$modal.msgError("保存成功但审核失败");
                                    }
                                }).catch(() => {
                                    this.$modal.msgError("保存成功但审核接口异常");
                                });
                            } else {
                                this.$modal.msgError("保存失败");
                            }
                        }).catch(() => {
                            this.$modal.msgError("保存接口异常");
                        }).finally(() => {
                            this.buttonLoading = false;
                            this.$tab.closeOpenPage('/machinery/compliehandle');
                        });

                }
            })
        },
        resetForm() {
            this.$refs['elForm'].resetFields()
        },
        async exportPDF() {
            const docxPath = '/registration.docx';  // DOCX 模板文件路径

            // 2. 获取 DOCX 模板文件并转换为 ArrayBuffer
            const response = await fetch(docxPath);
            const templateData = await response.arrayBuffer();

            const imageFields = ['renjiurl']; // 图片字段列表
            let imageData = null;
            let imageArrayBuffer= null;
            // 2. 获取图片数据并转换为 ArrayBuffer
            let imageArrayBufferList = {}; // 存储图片数据

            for (let field of imageFields) {
                // const file = this.tableData[this.selectMaterials].find(item=>item.key==field).file;
                if (this.form[field]) {
                    const file = this.form[field].replace('172.24.254.135','111.40.188.220')
                } else {
                    this.$modal.msgError("未获取到人机图片，请上传后导出");
                    return
                }
                

                if (file) {
                    // 获取图片数据并转换为 ArrayBuffer
                    imageData = await fetch(file);
                    imageArrayBuffer = await imageData.arrayBuffer();
                    
                    // 将图片数据存储到对象中
                    imageArrayBufferList[field] = imageArrayBuffer;
                    console.log('file', imageData,  imageArrayBuffer, imageArrayBufferList);
                    
                }
            }

            // 4. 使用 PizZip 处理 DOCX 文件
            const zip = new PizZip(templateData);  // 使用 pizzip 解压 DOCX 模板
            const doc = new docxtemplater(zip, {
                paragraphLoop: true,
                linebreaks: true,
                modules: [
                // 使用 ImageModule 插件插入图片
                new ImageModule({
                    getImage: (value, key) => imageArrayBufferList[key],
                    getSize: (afterValue, value, key) => {
                        // 设置不同图片的大小
                        // if (key === 'idCardFrontUrl') {
                        //     return [200, 100];  // 图片 1 设置为 400x300px
                        // }
                        if (key === 'renjiurl') {
                            return [300, 400];  // 图片 2 设置为 300x200px
                        }
                        return [100, 100];  // 默认图片大小为 200x200px
                        },
                    }),
                ],
            });

            // 5. 填充模板数据，替换占位符 {image1} 和 {image2}
            doc.render({
                regiNum: this.form.regiNum,
                machineType: this.form.machineType,
                speModel: this.form.speModel,
                power: this.form.power,
                machineEngine: this.form.machineEngine,
                machineNum: this.form.machineNum,
                price: this.form.price,
                moneySub: this.form.moneySub,
                productCompany: this.form.productCompany,
                productDate: this.form.productDate.substring(0, 10),
                saleCompany: this.form.saleCompany,
                saleDate: this.form.saleDate.substring(0, 10),
                invoice: this.form.invoice,
                appyBy: this.form.appyBy,
                idCard: this.form.idCard,
                bankCard: this.form.bankCard,
                phone: this.form.phone,

                renjiurl: 'renjiurl',  

            });

            // 6. 生成新的 DOCX 文件
            const blob = doc.getZip().generate({
                type: 'blob',
                mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            });

            // 7. 下载 DOCX 文件
            saveAs(blob, "2025年购置农业机械补贴核实登记信息表");  // 下载文件

            this.exportPDFStatus = true
        },
        handleSuccess(response, file, formFieldName) {
            console.log('上传成功:', response, file);
            if (response && response.code === 200) {
                const filePath = response.data.filePath;
                if (filePath) {
                    this.form[formFieldName] = filePath; // 将 ossId 保存到表单字段
                    this.$message.success('上传成功，已保存文件ID');
                    console.log('上传情况', this.form)

                } else {
                    this.$message.error('上传成功，但未返回 ossId');
                }
            } else {
                this.$message.error('上传失败，服务器返回错误');
            }
        },
        handlePreview(file) {            
            const serveIpPort = "111.40.188.220";
            let originalUrl = '';
            if (Object.keys(file).includes('url')) {
                originalUrl = file.url;
            } else if (file.response) {
                originalUrl = file.response.data.filePath;
            } else if (file.file) {
                originalUrl = file.file;
            }

            const fileUrl = originalUrl.replace(/http:\/\/[\d.]+/, `http://${serveIpPort}`);
            window.open(fileUrl);
        },
        handleExceed(files, fileList) {
            this.$message.warning(`当前限制选择 1 个文件，请删除现有文件后再选择新文件！`);
        },
        handleRemove(file, formFieldName) {
            delFile(file.response.data.ossId).then(response => {
                this.$message.success('删除成功');
                this.form[formFieldName] = undefined;
                console.log("保存的数据", this.form)
            }).catch(error => {
                this.$message.error('删除失败' + (error.message || '未知错误'));
            });
        },
    }
}
</script>
<style scoped>
.app-container {
    width: 80%;
    align-items: center;
    margin-left: 10%;

    /* border: 1px solid rgb(204, 28, 28); */
}

.card-container {
    position: relative;
    margin-top: 40px;
}

.infoDiv {
    width: 100%;
    align-items: center;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin-top: 20px;
    padding-top: 20px;
}

.corner-label {
    position: absolute;
    top: 0;
    left: 0;
    background: #81B337;
    /* 背景色 */
    color: white;
    /* 文字颜色 */
    padding: 2px 8px;
    /* 内边距 */
    font-size: 20px;
    /* 字体大小 */
    border-radius: 4px;
    /* 圆角，左上角和右下角有圆角（根据需求调整） */
    transform: translate(-10%, -10%);
    /* 微调位置，使其覆盖在圆角上 */
    /* 如果需要，可以设置z-index */
    z-index: 1;
}
</style>